#include "TFT_eSPI.h"
#include "Display.h"
#include "SPI.h"
#include "SPIFFS.h"
#include <FS.h>
#include "List_SPIFFS.h"
#include "Web_Fetch.h"

TFT_eSPI tft = TFT_eSPI(); // tft instance
U8g2_for_TFT_eSPI u8f;     // U8g2 font instance

#define FONT u8g2_font_wqy16_t_gb2312b

time_t prevDisplay = 0; // 显示时间
time_t weaterTime = 0;  // 显示天气

time_t getNtpTime();

long lastMqttConn = 0;
int showType = 0; // 0:展示时钟，1：展示图片

void checkNetStatus()
{
    // Wifi掉线重连
    if (WiFi.status() != WL_CONNECTED)
    {
        connectWifi();
    }

    // 非阻塞Mqtt重连，间隔30秒
     if (WiFi.status() == WL_CONNECTED)
     {
       long now = millis();
       if (!mqttClient.connected())
       {
         if (now - lastMqttConn > 30000)
         {
           lastMqttConn = now;
           connectMqtt();
         }
       }
       else
       {
         mqttClient.loop();
       }
     }
}

Weather weather;
Display display;

// This next function will be called during decoding of the jpeg file to
// render each block to the TFT.  If you use a different TFT library
// you will need to adapt this function to suit.
bool tft_output(int16_t x, int16_t y, uint16_t w, uint16_t h, uint16_t *bitmap)
{
    // Stop further decoding as image is running off bottom of screen
    if (y >= tft.height())
        return 0;

    // This function will clip the image block rendering automatically at the TFT boundaries
    tft.pushImage(x, y, w, h, bitmap);

    // This might work instead if you adapt the sketch to use the Adafruit_GFX library
    // tft.drawRGBBitmap(x, y, bitmap, w, h);

    // Return 1 to decode next block
    return 1;
}

/**
 *
 *图片解码初始化
 */
void setupJpg()
{
    // The jpeg image can be scaled by a factor of 1, 2, 4, or 8
    TJpgDec.setJpgScale(4);

    // The byte order can be swapped (set true for TFT_eSPI)
    TJpgDec.setSwapBytes(true);

    // The decoder must be given the exact name of the rendering function above
    TJpgDec.setCallback(tft_output);
}

WeatherData weatherData;

void setup()
{
    tft.begin();
    tft.setRotation(0);
    tft.fillScreen(TFT_WHITE);

    // u8f.begin(tft); // connect u8g2 procedures to TFT_eSPI
    // u8f.setFont(FONT);
    // u8f.setForegroundColor(TFT_BLACK); // apply color
    // u8f.setBackgroundColor(TFT_WHITE); // apply color

    // display.init(&tft, &u8f);
    Serial.begin(115200);

    if (!SPIFFS.begin())
    {
        Serial.println("SPIFFS initialisation failed!");
        while (1)
            yield(); // Stay here twiddling thumbs waiting
    }
    Serial.println("\r\nInitialisation done.");
    // // 背景
    // tft.fillRoundRect(0, 0, 128, 160, 5, TFT_WHITE);
    connectWifi();
    connectMqtt();

    // weatherData = weather.getCityWeater();
    // setSyncProvider(getNtpTime);

    // display.setupWeather(weatherData);
    // display.setUpClock();
    setupJpg();

    // displayText = "你好吗";
    // display.resetTextIndex();

    showType = 1;

    // This is for demoe purposes only so that file is fetched each time this is run
    if (SPIFFS.exists("/1.jpg") == true)
    {
        Serial.println("For test only, removing file");
        SPIFFS.remove("/1.jpg");
        // SPIFFS.remove("/F35.jpg");
    }
}
// 显示时钟
void showTime()
{
    // display.imgAnim();
    // display.textLoop();

    // if (now() != prevDisplay) {
    //     prevDisplay = now();

    //     display.setUpClock();
    // }
    // if (millis() - weaterTime > 60000) { // 5分钟更新一次天气
    //     weaterTime = millis();
    //     display.setupWeather(weather.getCityWeater());
    // }
}
// 显示图片
void showPicture()
{
    // List files stored in SPIFFS
    listSPIFFS();

    // Time recorded for test purposes
    uint32_t t = millis();

    // Fetch the jpg file from the specified URL, examples only, from imgur
    bool loaded_ok = getFile("http://111.230.11.3/picture/1.jpg", "/1.jpg"); // Note name preceded with "/"
    // bool loaded_ok = getFile("https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fsafe-img.xhscdn.com%2Fbw1%2Fa41d1478-b54f-4d26-a58f-1b1ff986037a%3FimageView2%2F2%2Fw%2F1080%2Fformat%2Fjpg&refer=http%3A%2F%2Fsafe-img.xhscdn.com&app=2002&size=f9999,10000&q=a80&n=0&g=0n&fmt=auto?sec=1708609533&t=43f234316b3ebd1a47deda2f4cee6ebf", "/3.jpg");

    t = millis() - t;
    if (loaded_ok)
    {
        Serial.print(t);
        Serial.println(" ms to download");
    }

    // List files stored in SPIFFS, should have the file now
    listSPIFFS();

    t = millis();

    // Now draw the SPIFFS file
    Serial.println("Start draw...");
    TJpgDec.drawFsJpg(0, 0, "/1.jpg");
    // TJpgDec.drawFsJpg(0, 0, "/F35.jpg");

    t = millis() - t;
    Serial.print(t);
    Serial.println(" ms to draw to TFT");

    // Wait forever
    while (1)
        yield();
}
void loop()
{
    if (showType == 1)
    {
        showPicture();
    }
    else
    {
        showTime();
    }
    checkNetStatus();
}
